package com.wxboot.game.eliminate.support;

import com.wxboot.game.eliminate.base.JellyCell;
import com.wxboot.game.eliminate.base.JellyType;

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JellyBeanGenerator {

    private static final SecureRandom random = new SecureRandom();
    private static final JellyType[] JELLY_TYPES = JellyType.values();
    private static final Map<Character, JellyType> JELLY_TYPE_MAP = new HashMap<>();

    static {
        Arrays.stream(JellyType.values()).forEach(jellyType -> {
            JELLY_TYPE_MAP.put(jellyType.type, jellyType);
        });
    }

    public static List<JellyCell[][]> initJellyMatrixList(int levelNum, int cellNum) {
        List<JellyCell[][]> jellyMatrixList = new ArrayList<>();
        for (int i = 0; i < levelNum; i++) {
            jellyMatrixList.add(initJellyMatrix(cellNum));
        }

        return jellyMatrixList;
    }

    public static JellyCell[][] initJellyMatrix(int cellNum) {
        JellyCell[][] jellyMatrix = new JellyCell[cellNum][cellNum];
        for (int i = 0; i < cellNum; i++) {
            JellyCell[] jellyCells = randomJellyCells(cellNum);
            jellyMatrix[i] = jellyCells;
        }

        return jellyMatrix;
    }

    public static JellyCell randomJellyCell() {
        int r = random.nextInt(100);
        if (r < 25) {
            r = random.nextInt(4);
        } else {
            r = 0;
        }
        JellyType jellyType = JELLY_TYPES[r];
        return new JellyCell(jellyType);
    }

    public static JellyCell[] randomJellyCells(int cellNum) {
        JellyCell[] jellyCells = new JellyCell[cellNum];
        for (int i = 0; i < cellNum; i++) {
            jellyCells[i] = randomJellyCell();
        }

        return jellyCells;
    }

    public static JellyCell[][] deserializeMatrix(String matrixStr) {
        String[] matrixArr = matrixStr.split("\n");
        JellyCell[][] jellyMatrix = new JellyCell[matrixArr.length][matrixArr[0].length()];
        for (int i = 0; i < matrixArr.length; i++) {
            for (int j = 0; j < matrixArr[i].length(); j++) {
                JellyType jellyType = JELLY_TYPE_MAP.get(matrixArr[i].charAt(j));
                jellyMatrix[i][j] = new JellyCell(jellyType);
            }
        }

        return jellyMatrix;
    }

}
